package heartbeat

import (
	"math/rand"
	"strconv"
	"sync"
	"time"
	"tsuhi_api_server/conf"
	"tsuhi_api_server/mqs/rabbitmq"
)

var dataServer = make(map[string]time.Time)
var mutex sync.Mutex

var config *conf.Config

func init() {
	config = conf.StorageRoot()
}

func ListenHeart() {

	mq := rabbitmq.New(config.Server.RabbitServer)
	defer mq.Close()
	mq.Bind("apiServer")
	consume := mq.Consume()
	go removeExpiredDataServer()
	for msg := range consume {
		data, err := strconv.Unquote(string(msg.Body))
		if err != nil {
			panic(err)
		}
		mutex.Lock()
		dataServer[data] = time.Now()
		mutex.Unlock()
	}
}

func removeExpiredDataServer() {
	for {
		time.Sleep(time.Second * 5)
		mutex.Lock()
		for s, t := range dataServer {
			if t.Add(10 * time.Second).Before(time.Now()) {
				delete(dataServer, s)
			}
		}
		mutex.Unlock()
	}
}

func GetDataServer() []string {
	mutex.Lock()
	defer mutex.Unlock()
	ds := make([]string, 0)

	for s, _ := range dataServer {
		ds = append(ds, s)
	}
	return ds
}

func ChooseRandomDataServer() string {
	server := GetDataServer()
	n := len(server)
	if n == 0 {
		return ""
	}
	return server[rand.Intn(n)]
}
